#coding=utf-8
import urllib2
import wsgiref.handlers

import httplib2
from BeautifulSoup import BeautifulSoup

from google.appengine.ext import webapp

import stcode, stcode2

class MainPage(webapp.RequestHandler):
  def get(self):
    self.response.out.write('hello world')

#url = 'http://www.douban.com'
class URLFetchTest(webapp.RequestHandler):
  def get(self):
    url = self.request.get('url')
    
    f = urllib2.urlopen(url)
    data = f.read()
    self.response.out.write(data)

class Httplib2Test(webapp.RequestHandler):
  def get(self):  
    #url = self.request.get('url')
    h = httplib2.Http()
    resp, content = h.request("http://www.python.org/", "GET") 
    
    self.response.out.write(resp)
    self.response.out.write('\n')
    self.response.out.write(content)

class ShStcodeTest(webapp.RequestHandler):
  def get(self):  
    cns = stcode.get_shstcode()
    for cn in cns:
        self.response.out.write( "%s:%s"%(cn[0], cn[1]) )
        self.response.out.write('<br/>')

class SzStcodeTest(webapp.RequestHandler):
  def get(self):  
    cns = stcode.get_szstcode()
    for cn in cns:
        self.response.out.write( "%s:%s"%(cn[0], cn[1]) )
        self.response.out.write('<br/>')

class StcodeTest(webapp.RequestHandler):
  def get(self):
    market = self.request.get('m')
    if market:
        codes = stcode2.get_code(market)
    else:
        codes = stcode2.get_code()
        
    for c in codes:
        self.response.out.write( "%s"%c )
        self.response.out.write('<br/>')
                       
application = webapp.WSGIApplication([
  ('/', MainPage),
  ('/urlfetch', URLFetchTest),
  ('/httplib2', Httplib2Test),
  ('/sh_code', ShStcodeTest),
  ('/sz_code', SzStcodeTest),
  ('/stcode', StcodeTest)
], debug=True)

def main():
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()
